package in.abip.chisame;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * Setting activity.
 * @author Julot
 * @since Tuesday, February 22, 2011
 */
public class SettingsActivity extends Activity {
	public static final String HARDWARE = "hardware";
	public static final String IP = "ip";
	public static final String PORT = "port";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_activity);
		bindApply();
		bindCancel();
		readSettings();
	}
	
	protected void bindApply() {
		Button button = (Button) findViewById(R.id.apply);
		button.setOnClickListener(
			new OnClickListener() {
				public void onClick(View v) {
					writeSettings();
					SettingsActivity.this.finish();
				}
			}
		);
	}
	
	protected void bindCancel() {
		Button button = (Button) findViewById(R.id.cancel);
		button.setOnClickListener(
			new OnClickListener() {
				public void onClick(View v) {
					SettingsActivity.this.finish();
				}
			}
		);
	}
	
	protected void readSettings() {
		EditText ip = (EditText) findViewById(R.id.ip);
		EditText port = (EditText) findViewById(R.id.port);
		SharedPreferences pref = getSharedPreferences(
			HARDWARE,
			Context.MODE_PRIVATE
		);
		if (pref.contains(IP)) {
			ip.setText(pref.getString(IP, "192.168.0.1"));
		}
		if (pref.contains(PORT)) {
			port.setText(Integer.toString(pref.getInt(PORT, 23)));
		}
	}
	
	protected void writeSettings() {
		EditText ip = (EditText) findViewById(R.id.ip);
		EditText port = (EditText) findViewById(R.id.port);
		SharedPreferences pref = getSharedPreferences(
			HARDWARE,
			Context.MODE_PRIVATE
		);
		Editor editor = pref.edit();
		editor.putString(IP, ip.getText().toString());
		editor.putInt(PORT, Integer.parseInt(port.getText().toString()));
		editor.commit();
	}
}
